<?php

/**
 * @Author: wuchenge
 * @Date:   2021-12-10 17:36:38
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Admin\Controllers;

use App\Http\Controllers\ApiController;
use App\Libraries\JwtToken;
use App\Models\Admin;
use App\Requests\Admin\LoginRequest;
use App\Services\BoardDataService;
use App\Transformer\AdminTransformer;
use Illuminate\Http\Request;

class IndexController extends ApiController
{
    /**
     * @var mixed
     */
    protected $admin_transformer;

    /**
     * @param AdminTransformer $admin_transformer
     */
    public function __construct(AdminTransformer $admin_transformer)
    {
        $this->admin_transformer = $admin_transformer;
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function nums(Request $request)
    {
        $res = BoardDataService::getBoardData();
        return $this->response($res);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function refresh(Request $request)
    {
        $user    = $request->get('admin');
        $payload = [
            'id' => $user->id,
        ];

        $data = [
            'token' => JwtToken::createToken($payload),
            'user'  => $this->admin_transformer->transform($user),
        ];

        return $this->response($data);
    }

    /**
     * @param LoginRequest $request
     * @return mixed
     */
    public function login(LoginRequest $request)
    {
        // 帐号
        $username = $request->input('mobile');
        // 密码
        $password = $request->input('captcha');

        // if (!config('app.debug')) {
        //     // 验证图片码
        //     if (!captcha_api_check($request->captcha, $request->key)) {

        //         return $this->setErrorCode(1, '验证码错误')->response();
        //     }
        // }

        $admin = Admin::where('username', $username)->first();

        if (!$admin) {
            return $this->failed('没有找到此用户');
        }

        if ($admin->pwd != Admin::encodePassword(md5($password))) {
            return $this->failed('密码错误');
        }

        if ($admin->status == Admin::STATUS_NO) {
            return $this->failed('用户被禁用');
        }

        // 更新最后登录时间
        $admin->fill(['updated_at' => date('Y-m-d H:i:s')])->save();

        $payload = [
            'id'        => $admin->id,
            'nick_name' => $admin->nick_name,
        ];

        $data = [
            'token' => JwtToken::createToken($payload),
            'admin' => $this->admin_transformer->transform($admin),
        ];

        return $this->response($data);
    }

    /**
     * @return mixed
     */
    public function captcha()
    {
        return $this->response(app('captcha')->create('default', true));
    }
}
